import { ColumnProps } from "@/components/ProTable/interface";
import { ElForm } from "element-plus";
import { getCurrentInstance, defineComponent, ComponentInternalInstance } from "vue";
import ProTable from "@/components/ProTable/index.vue";
import "./../alarm.scss";
import { addDeviceAlarm, getDeviceAlarmConfig } from "@/api/modules/iot/alarm";
import { useRoute } from "vue-router";
import { showTips, confirm } from "@/utils/util";
import { alarmParam } from "@/utils/constants";
import { getDictList } from "@/utils/cacheUtil";
import DialogBox from "@/components/DialogBox";
import { addDict } from "@/api/modules/system/dict";
export default defineComponent({
	props: {
		sn: String,
		title: String,
		sensorKey: {
			type: String,
			default() {
				return "";
			}
		}
	},
	emits: ["change"],
	setup(props, { emit, expose }) {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const route = useRoute();
		type FormInstance = InstanceType<typeof ElForm>;
		const formRef = ref<FormInstance>();
		let configFormData = reactive<any>({
			//告警类型
			alarmType: "",
			//自动处理
			autoDone: false,
			//设备告警
			devCustomWarn: true,
			//是否故障
			isError: 0,
			//阈值上线
			threshold: null,
			//触发方式:1=首次告警，2=每次告警
			triggerType: 1,
			//越上下线
			warningDlimit: null,
			//越下限
			warningElimit: null,
			//越上限
			warningUlimit: null,
			//告警级别
			warningLevel: 1,
			//告警模式
			warningMode: 1,
			//设备告警=0、平台告警=1
			warningType: 1,
			//告警原因
			alarmReason: null,
			//处理意见
			suggestion: null
		});
		const formRules = ref<any>({});
		const tableRecords = ref<any[]>([]);
		watchEffect(() => {
			if (configFormData.warningMode == 1) {
				formRules.value = {
					warningUlimit: [{ required: true, message: proxy?.$t("alarm_configdetail.formrules.ulimit"), trigger: "change" }]
				};
				configFormData.warningDlimit = "";
				configFormData.warningElimit = "";
			} else if (configFormData.warningMode == 2) {
				formRules.value = {
					// alarmType: [{ required: true, message: "请设置告警类型", trigger: "change" }],
					warningDlimit: [{ required: true, message: proxy?.$t("alarm_configdetail.formrules.dlimit"), trigger: "change" }]
				};
				configFormData.warningUlimit = "";
				configFormData.warningElimit = "";
			} else if (configFormData.warningMode == 3) {
				formRules.value = {
					// alarmType: [{ required: true, message: "请设置告警类型", trigger: "change" }],
					warningUlimit: [{ required: true, message: proxy?.$t("alarm_configdetail.formrules.ulimit"), trigger: "change" }],
					warningDlimit: [{ required: true, message: proxy?.$t("alarm_configdetail.formrules.dlimit"), trigger: "change" }]
				};
				configFormData.warningElimit = "";
			} else if (configFormData.warningMode == 4) {
				formRules.value = {
					// alarmType: [{ required: true, message: "请设置告警类型", trigger: "change" }],
					warningElimit: [{ required: true, message: proxy?.$t("alarm_configdetail.formrules.elimit"), trigger: "change" }]
				};
				configFormData.warningDlimit = "";
				configFormData.warningUlimit = "";
			} else {
				configFormData.warningElimit = "";
				configFormData.warningDlimit = "";
				configFormData.warningUlimit = "";
			}
			formRules.value.alarmType = [
				{ required: true, message: proxy?.$t("alarm_configdetail.formrules.alarm_name"), trigger: "change" },
				{
					validator: (rule: any, value: any, callback: any) => {
						if (!isModify.value && tableRecords.value.find(item => item.alarmType == value)) {
							callback(new Error(proxy?.$t("alarm_configdetail.errMsg.alarm_exists")));
						} else {
							callback();
						}
					},
					trigger: "blur"
				}
			];
		});
		const addList = () => {
			(formRef.value as FormInstance).validate(async valid => {
				if (!valid) {
					return;
				}
				configFormData.threshold = configFormData.warningElimit;
				configFormData.warningDlimit = configFormData.warningDlimit ? Number(configFormData.warningDlimit) : null;
				configFormData.warningUlimit = configFormData.warningUlimit ? Number(configFormData.warningUlimit) : null;
				configFormData.warningElimit = configFormData.warningElimit ? Number(configFormData.warningElimit) : null;
				if (isModify.value) {
					tableRecords.value[currtentRowIndex.value] = configFormData;
				} else {
					tableRecords.value.push(JSON.parse(JSON.stringify(configFormData)));
				}
				saveDeviceAlarm();
			});
		};
		const saveBtnLabel = ref(proxy?.$t("alarm_configdetail.btn.add"));
		const saveDeviceAlarm = async () => {
			tableRecords.value = tableRecords.value.map((item: any) => {
				item.name = props.title || tableRecords.value[0].name;
				return item;
			});
			let { code, message } = await addDeviceAlarm({
				sn: props.sn || route.query.sn,
				key: props.sensorKey,
				warning: tableRecords.value,
				devProductId: route.query.id,
				productCode: route.query.productModel
			});
			let ok = showTips(code, proxy?.$t("alarm_configdetail.tips.add_alarm_config"), message);
			if (ok) {
				(formRef.value as FormInstance).resetFields();
				emit("change");
				// resetForm();
				proTable.value.getTableList();
				isModify.value = false;
				currtentRowIndex.value = "";
				saveBtnLabel.value = proxy?.$t("alarm_configdetail.btn.add");
			}
		};

		const buttonsList = reactive([
			{ path: "del", title: proxy?.$t("alarm_configdetail.btn.del"), type: "danger" },
			{ path: "detail", title: proxy?.$t("alarm_configdetail.btn.detail"), type: "primary" }
		]);
		const dicts = reactive({
			...alarmParam
		});
		const warningLevel = ref<any>([]);
		const alarmType = ref<any>([]);
		onMounted(async () => {
			warningLevel.value = await getDictList("warning_level");
			alarmType.value = await getDictList("alarm_type");
		});
		//是否是编辑
		const isModify = ref(false);
		const currtentRowIndex = ref();
		const handerBtn = async (fn: string, row: any) => {
			switch (fn) {
				case "del":
					confirm({ content: proxy?.$t("alarm_configdetail.confirm.del") }).then((flag: any) => {
						if (flag) {
							tableRecords.value.splice(row.rowIndex, 1);
							saveDeviceAlarm();
						}
					});
					break;
				case "staging":
					addList();
					break;
				case "detail":
					currtentRowIndex.value = row.rowIndex;
					isModify.value = true;
					for (const key in row.row) {
						configFormData[key] = row.row[key];
					}
					saveBtnLabel.value = proxy?.$t("alarm_configdetail.btn.save");
					break;
				case "reset":
					(formRef.value as FormInstance).resetFields();
					isModify.value = false;
					currtentRowIndex.value = "";
					saveBtnLabel.value = proxy?.$t("alarm_configdetail.btn.add");
					break;
			}
		};
		const proTable = ref<any>();
		const columns: ColumnProps[] = [
			// { type: "selection", fixed: "left", width: "auto" },
			{ prop: "alarmType", label: proxy?.$t("alarm_configdetail.tablist_label.alarm_type") },
			{ prop: "autoDone", label: proxy?.$t("alarm_configdetail.tablist_label.auto_done") },
			{ prop: "isError", label: proxy?.$t("alarm_configdetail.tablist_label.is_error") },
			{ prop: "triggerType", label: proxy?.$t("alarm_configdetail.tablist_label.trigger_type") },
			{ prop: "warningElimit", label: proxy?.$t("alarm_configdetail.tablist_label.elimit") },
			{ prop: "warningLevel", label: proxy?.$t("alarm_configdetail.tablist_label.level"), width: "100" },
			{ prop: "warningMode", label: proxy?.$t("alarm_configdetail.tablist_label.mode") },
			{ prop: "operation", label: proxy?.$t("alarm_configdetail.tablist_label.operation"), fixed: "right", width: 130 }
		];
		const alarmId = ref();
		const dataCallback = (data: any) => {
			tableRecords.value = data[0]?.warning || [];
			alarmId.value = data[0]?.id || "";
			return {
				datalist: data[0]?.warning || []
				// total: data.total || 0
				// pageIndex: data.current,
				// pageSize: data.size
			};
		};
		const getTableList = async () => {
			return getDeviceAlarmConfig({
				sn: route.query.id ? "" : props.sn || route.query.sn,
				key: props.sensorKey,
				productId: route.query.id || ""
			});
		};
		expose({});
		const alarmTypeDialog = reactive({ visible: false, value: "" });
		const saveAlarmTypeDict = async () => {
			let { code, message } = await addDict({
				status: 1,
				dictType: "alarm_type",
				dictTypeName: "告警类型",
				dictLabel: alarmTypeDialog.value,
				dictValue: JSON.stringify({ type: "string", value: alarmTypeDialog.value }),
				dictSort: null
			});
			let ok = showTips(code, proxy?.$t("alarm_configdetail.tips.dictionary"), message);
			if (ok) {
				alarmType.value = await getDictList("alarm_type", true);
				alarmTypeDialog.visible = false;
				configFormData.alarmType = alarmTypeDialog.value;
			}
		};
		return () => {
			return (
				<div class="alarm-config-detail">
					<DialogBox
						v-model:visible={alarmTypeDialog.visible}
						width="400"
						title={proxy?.$t("alarm_configdetail.dialog_title.add_type")}
						onConfirm={saveAlarmTypeDict}
					>
						<el-input v-model={alarmTypeDialog.value}></el-input>
					</DialogBox>
					<el-form ref={formRef} rules={formRules} label-width="100px" model={configFormData} validate-on-rule-change={false}>
						<div class="grid grid-cols-3">
							<el-form-item label={proxy?.$t("alarm_configdetail.form_label.alarm_type")} prop="alarmType" class="col-span-1">
								<div class="flex w-full">
									<el-select v-model={configFormData.alarmType} filterable class="flex-1">
										{alarmType.value.map((item: any) => {
											return <el-option value={item.key} label={item.label}></el-option>;
										})}
									</el-select>
									<div
										class="w-16 text-center cursor-cell hover:text-blue-800"
										onClick={() => {
											alarmTypeDialog.visible = true;
										}}
									>
										{proxy?.$t("alarm_configdetail.btn.add")}
									</div>
								</div>
							</el-form-item>
							<el-form-item label={proxy?.$t("alarm_configdetail.form_label.level")} prop="warningLevel" class="col-span-1">
								<el-select v-model={configFormData.warningLevel}>
									{warningLevel.value.map((item: any) => {
										return <el-option value={item.key} label={item.label}></el-option>;
									})}
								</el-select>
							</el-form-item>
						</div>
						<div class="grid grid-cols-3">
							<el-form-item label={proxy?.$t("alarm_configdetail.form_label.mode")} prop="warningMode" class="col-span-1">
								<el-select v-model={configFormData.warningMode}>
									{Object.values(dicts.warningMode).map((item: any) => {
										return <el-option value={item.value} label={item.label}></el-option>;
									})}
								</el-select>
							</el-form-item>
							{configFormData.warningMode == 5 ? null : (
								<>
									{configFormData.warningMode == 1 || configFormData.warningMode == 3 ? (
										<el-form-item
											label={proxy?.$t("alarm_configdetail.form_label.ulimit")}
											prop="warningUlimit"
											class="col-span-1"
										>
											<el-input
												v-model={configFormData.warningUlimit}
												placeholder={proxy?.$t("alarm_configdetail.placeholder.ulimit")}
												type="number"
											/>
										</el-form-item>
									) : null}
									{configFormData.warningMode == 2 || configFormData.warningMode == 3 ? (
										<el-form-item
											label={proxy?.$t("alarm_configdetail.form_label.dlimit")}
											prop="warningDlimit"
											class="col-span-1"
										>
											<el-input
												v-model={configFormData.warningDlimit}
												placeholder={proxy?.$t("alarm_configdetail.placeholder.dlimit")}
												type="number"
											/>
										</el-form-item>
									) : null}
									{configFormData.warningMode == 4 ? (
										<el-form-item
											label={proxy?.$t("alarm_configdetail.form_label.elimit")}
											prop="warningElimit"
											class="col-span-1"
										>
											<el-input
												v-model={configFormData.warningElimit}
												placeholder={proxy?.$t("alarm_configdetail.placeholder.elimit")}
												type="number"
											/>
										</el-form-item>
									) : null}
								</>
							)}
						</div>
						<div class="grid grid-cols-3">
							<el-form-item label={proxy?.$t("alarm_configdetail.form_label.is_rrror")} prop="" class="col-span-1">
								<el-radio-group v-model={configFormData.isError}>
									{Object.values(dicts.isError).map((item: any) => {
										return <el-radio label={item.value}>{item.label}</el-radio>;
									})}
								</el-radio-group>
							</el-form-item>
							<el-form-item label={proxy?.$t("alarm_configdetail.form_label.auto_done")} prop="" class="col-span-1">
								<el-radio-group v-model={configFormData.autoDone}>
									{Object.values(dicts.autoDone).map((item: any) => {
										return <el-radio label={item.value}>{item.label}</el-radio>;
									})}
								</el-radio-group>
							</el-form-item>
							<el-form-item label={proxy?.$t("alarm_configdetail.form_label.trigger_type")} prop="" class="col-span-1">
								<el-radio-group v-model={configFormData.triggerType}>
									{Object.values(dicts.triggerType).map((item: any) => {
										return <el-radio label={item.value}>{item.label}</el-radio>;
									})}
								</el-radio-group>
							</el-form-item>
						</div>
						<el-form-item label={proxy?.$t("alarm_configdetail.form_label.reason")} prop="alarmReason" class="col-span-1">
							<el-input
								type="textarea"
								v-model={configFormData.alarmReason}
								placeholder={proxy?.$t("alarm_configdetail.placeholder.alarm_reason")}
							/>
						</el-form-item>
						{dicts.autoDone.auto.value == configFormData.autoDone ? (
							<el-form-item label={proxy?.$t("alarm_configdetail.form_label.suggestion")} prop="suggestion" class="col-span-1">
								<el-input
									type="textarea"
									v-model={configFormData.suggestion}
									placeholder={proxy?.$t("alarm_configdetail.placeholder.suggestion")}
								/>
							</el-form-item>
						) : null}
						{/* <el-form-item>
							<el-button type="primary">暂存</el-button>
							<el-button type="primary">提交</el-button>
						</el-form-item> */}
					</el-form>

					<div class="mt-4 ignore-search-split">
						<ProTable
							showSearch={false}
							ref={proTable}
							columns={columns}
							requestApi={getTableList}
							dataCallback={dataCallback}
							pagination={false}
						>
							{{
								tableHeader: (scope: any) => {
									return (
										<>
											<el-button onClick={() => handerBtn("staging", scope)} type="primary">
												{saveBtnLabel.value}
											</el-button>
											<el-button onClick={() => handerBtn("reset", scope)}>{proxy?.$t("common.btn.reset")}</el-button>
										</>
									);
								},
								alarmType: (scope: any) => {
									return (
										<el-link type="primary" onClick={() => handerBtn("detail", scope)}>
											{scope.row.alarmType}
										</el-link>
									);
								},
								warningMode: (scope: any) => {
									return Object.values(dicts.warningMode).find((item: any) => item.value == scope.row.warningMode)?.label;
								},
								warningLevel: (scope: any) => {
									return warningLevel.value.find((item: any) => item.key == scope.row.warningLevel)?.label;
								},
								isError: (scope: any) => {
									return Object.values(dicts.isError).find((item: any) => item.value == scope.row.isError)?.label;
								},
								autoDone: (scope: any) => {
									return Object.values(dicts.autoDone).find((item: any) => item.value == scope.row.autoDone)?.label;
								},
								triggerType: (scope: any) => {
									return Object.values(dicts.triggerType).find((item: any) => item.value == scope.row.triggerType)?.label;
								},
								warningType: (scope: any) => {
									return Object.values(dicts.warningType).find((item: any) => item.value == scope.row.warningType)?.label;
								},
								warningElimit: (scope: any) => {
									if (scope.row.warningMode == 1) {
										return scope.row.warningUlimit;
									} else if (scope.row.warningMode == 2) {
										return scope.row.warningDlimit;
									} else if (scope.row.warningMode == 3) {
										return scope.row.warningUlimit + "~" + scope.row.warningDlimit;
									} else if (scope.row.warningMode == 4) {
										return scope.row.warningElimit;
									}
									return Object.values(dicts.triggerType).find(item => item.value == scope.row.triggerType)?.label;
								},
								operation: (scope: any) => {
									return buttonsList.map((item: any) => {
										return (
											<el-link class={`iconfont ${item.icon}`} onClick={() => handerBtn(item.path, scope)} type={item.type}>
												{item.title}
											</el-link>
										);
									});
								}
							}}
						</ProTable>
					</div>
				</div>
			);
		};
	}
});
